//
//  HJSystemMsgVC.m
//  project
//
//  Created by hu on 2019/4/1.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJSystemMsgVC.h"
#import "HJSystemMsgCell.h"
#import "HJChatRoomVC.h"

@interface HJSystemMsgVC ()
@property (nonatomic,strong) NSMutableArray <HJSystemModel *>* dataArray;
@end

@implementation HJSystemMsgVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"系统消息";
    [self loadNetworkData];
    self.rightNavTitle = @"全部已读";
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithHex:0x999999];
}

-(void)configTableView {
    self.needRefresh = YES;
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 37, 0, 0);
    self.tableView.rowHeight = 65;
    self.tableView.estimatedRowHeight = UITableViewAutomaticDimension;
}

/**
 全部已读
 */
-(void)didClickRightNavAction {
    NSString * url = [Api stringByAppendingString:ReadNoticeBatchApi];
    NSMutableString *noticeIdMutable = [NSMutableString string];
    NSMutableArray * modelArr = [NSMutableArray arrayWithCapacity:self.dataArray.count];
    for (HJSystemModel * systemModel in self.dataArray) {
        if (!systemModel.isRead) {
            [noticeIdMutable appendFormat:@"%@,",systemModel.noticeId];
        }
        systemModel.isRead = YES;
        [modelArr addObject:systemModel];
    }
    if (!noticeIdMutable.length) {
        [self showErrorHUDWithError:@"暂无未读消息！"];
        return;
    }
    [HJHttpTool post:url params:@{@"noticeIds":noticeIdMutable} success:^(HJResponeds *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [mNotificationCenter postNotificationName:NotificationClearSystem object:nil];
            self.dataArray = modelArr;
            [self.tableView reloadData];
        });
    } failure:^(id result) {
        [self showErrorHUDWithError:result];
    }];
}

-(NSMutableArray<HJSystemModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
    }
    return _dataArray;
}

-(void)loadNetworkData {
    NSString * url = [Api stringByAppendingString:NoticePageApi];
    [HJHttpTool post:url params:@{@"userId":[HJUserManager getUserModel].userId,@"pageCurrent":@(self.page)} success:^(HJResponeds *result) {
        self.totalPage = result.data[@"pages"];
        if (self.page==1) {
            [self.dataArray removeAllObjects];
        }
        NSArray * arr = [NSArray yy_modelArrayWithClass:[HJSystemModel class] json:result.data[@"records"]];
        [self.dataArray addObjectsFromArray:arr];
        [self.tableView reloadData];
        [self.tableView endRefresh];
    } failure:^(id result) {
        [self.tableView endRefresh];
        [self showErrorHUDWithError:result];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJSystemMsgCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"HJSystemMsgCell" owner:nil options:nil].firstObject;
    }
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction * deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSString * url = [Api stringByAppendingString:DeleteNoticeApi];
        HJSystemModel * model = self.dataArray[indexPath.row];
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        params[@"noticeId"] = model.noticeId;
        params[@"userId"] = [HJUserManager getUserModel].userId;
        WS(weakSelf)
        [HJHttpTool post:url params:params success:^(HJResponeds *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf showSuccessHUDWithStr:@"删除成功"];
                [weakSelf.dataArray removeObject:model];
                [tableView reloadData];
            });
        } failure:^(id result) {
            [weakSelf showErrorHUDWithError:result];
        }];
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    return @[deleteAction];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJSystemModel * model = self.dataArray[indexPath.row];
    HJChatRoomVC * chatRoomVC = [[UIStoryboard storyboardWithName:@"Chat" bundle:nil]instantiateViewControllerWithIdentifier:chatRoom];
    RCConversationModel * conversationModel = [[RCConversationModel alloc]init];
    conversationModel.conversationTitle = model.user.nickName;
    conversationModel.conversationType = ConversationType_PRIVATE;
    conversationModel.targetId = model.user.userId;
    chatRoomVC.conversationModel = conversationModel;
    [self.navigationController pushViewController:chatRoomVC animated:YES];
}

@end


@implementation HJSystemModel

- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
    [self transformProperties];
    return YES;
}

- (NSString *)description {
    return [self yy_modelDescription];
}

-(void)transformProperties {
    NSString * imageStr;
    switch (self.type) {
        case 1:
            imageStr = @"";
            break;
        case 2:
            imageStr = @"system_star";
            break;
        case 3:
            imageStr = @"system_zudui";
            break;
        case 4:
            imageStr = @"systempiao";
            break;
        default:
            break;
    }
    self.imageName = imageStr;
}

@end
